package handlers

// WebSocket 处理器：处理 WebSocket 连接、消息收发
import (
	"iot_gateway/internal/service"
	"iot_gateway/models"
	"net/http"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许所有来源
	},
}

type LocalBroadcastMessage struct {
	*models.BroadcastMessage
}
func NewLocalBroadcastMessage(origin *models.BroadcastMessage) *LocalBroadcastMessage {
	return &LocalBroadcastMessage{
		BroadcastMessage: origin,
	}
}

func (lb *LocalBroadcastMessage) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
	//升级为 WebSocket 连接，失败则返回错误
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		http.Error(w, "Failed to upgrade to WebSocket", http.StatusBadRequest)
		return
	}
	//连接成功后，将客户端添加到广播列表

	lb.Lock.Lock()
	lb.Clients[conn] = true
	lb.Lock.Unlock()
	defer func() {
		lb.Lock.Lock()
		delete(lb.Clients, conn) //移除客户端
		lb.Lock.Unlock()
		conn.Close() //关闭连接
	}()
	//首次链接发送全量数据
	initialData := service.GetDeviceStatusFromDB()
	conn.WriteJSON(initialData)
	// 保持连接（只读）
	for {
		if _, _, err := conn.ReadMessage(); err != nil {
			break
		}
	}
}
